const express = require('express');
let router = express.Router();
let { verifyToken } = require('../utils/token');
let Db = require('../utils/db完整');
let formidable = require('formidable');
let timeStamp = require('time-stamp');
let path = require("path");
let fs = require('fs');
let apiUrl = require('../config/config');
const md5 = require('md5');
let { api_url } = apiUrl;

//token验证使用中间件
router.use((req, res, next) => {
  if (req.headers.authorization == 'null') {//验证是否登录
    next('请先登录');
    return;
  }
  if (!verifyToken(req.headers.authorization)) {//验证是否过期
    next('登录已过期，重新登录');
    return;
  }
  next();
})

//渲染默认个人信息
router.get('/user', async (req, res, next) => {
  //token验证---中间件use处理
  let { mid } = verifyToken(req.headers.authorization);
  //根据mid查询并获取用户信息
  let sql = `SELECT 
  id,
  mid,
  realname,
  username,
  sex,
  birthdate,
  telphone,
  CONCAT('${api_url}','/uploads/','head/',head_photo_url) AS head_photo_url 
  FROM e_member WHERE mid='${mid}'`
  let [err, results] = await Db(sql);
  // console.log(err, '出错');
  // console.log(results, '请求结果');
  if (err) {
    next([err, '请求个人信息出错']);
    return;
  };
  if (results.length <= 0) {
    next('当前无此用户');
    return;
  };
  res.send({
    status: 200,
    msg: '请求个人信息成功',
    results: results[0]
  })
});

//更新头像
router.post('/uploadhead', (req, res, next) => {
  //token验证---中间件use处理
  let { mid } = verifyToken(req.headers.authorization);
  let form = formidable({
    // 临时上传文件目录-绝对路径 __dirname指app里面的routes
    uploadDir: path.join(__dirname, "../uploads/head/temp")
  });
  form.parse(req, async (err, fields, files) => {
    if (err) {
      next("头像上传失败")
      return
    };
    //重命名
    //path.extname(__filename))获取文件的后缀名，
    //files.name就是files里面的文件名！！
    //files.path就是files里面的文件路径！！
    let newname = timeStamp('YYMMDDHHmmssms') + path.extname(files.headPortrait.name);
    //__dirname指app里面的routes
    let newPath = path.join(__dirname, "../uploads/head", newname);
    let oldPath = files.headPortrait.path;
    fs.renameSync(oldPath, newPath);

    //更改数据库里面头像名称
    let sql = `UPDATE e_member SET head_photo_url="${newname}" WHERE mid="${mid}"`;
    let [err1, results] = await Db(sql);
    if (err1) {
      alert([err1, '头像数据库名称修改出错']);
      return;
    };
    res.send({
      status: 200,
      msg: "头像更新成功",
      results: `${api_url}/uploads/head/${newname}` //后端图片存在地址       
    })
  });


})

//更新其他用户信息
router.put('/user', async (req, res, next) => {
  //token验证---中间件use处理
  let { mid } = verifyToken(req.headers.authorization);
  let { realname, username, sex, birthdate, telphone } = req.body;
  let sql = `UPDATE e_member SET
  realname='${realname}',
  username='${username}',
  sex='${sex}',
  birthdate='${birthdate}',
  telphone='${telphone}'
  WHERE mid='${mid}'
  `;

  let [err, results] = await Db(sql);
  console.log(err, '修改信息出错');
  console.log(results, '修改信息ok');
  if (err) {
    next([err, '请求修改个人信息出错']);
    return;
  };
  res.send({
    status: 200,
    msg: '修改个人信息成功',
    results,
  })
})

//渲染我的课程
router.get('/orders', async (req, res, next) => {
  //token验证---中间件use已经处理
  let { mid } = verifyToken(req.headers.authorization);
  console.log(mid);
  // let {page,size}=req.query;
  //请求总页码
  let sqlA = `SELECT oid,
  e_course.cid,
  title,subject_name,
  area_name,
  CONCAT('${api_url}','/uploads/','online/',image_src) AS image_src 
  FROM e_order
  JOIN e_course
  ON e_order.cid=e_course.cid
  WHERE mid='${mid}'`;

  //92f9793a-7c42-45c3-895b-4f6f1845def4
  //${mid}
  let [err, results] = await Db(sqlA);
  console.log(err, '课程订单出错');
  console.log(results.length, '课程订单');
  if (err) {
    next([err.sqlMessage, '课程订单请求失败'])
    return;
  };
  console.log(results.length, '课程数量');

  res.send({
    status: 200,
    msg: '课程订单请求成功',
    results
  })
});

//修改密码
router.put('/password', async (req, res, next) => {
  //token验证---中间件use已经处理
  let { mid } = verifyToken(req.headers.authorization);
  let { passOld, passNew } = req.body;
  //旧密码先匹配
  //SELECT  *  FROM  student    WHERE  age=10; 
  let sqlO = `SELECT * FROM  e_member WHERE password='${md5(md5(passOld))}'and mid='${mid}'`;
  let [errO, resultsO] = await Db(sqlO);
  console.log(resultsO, '旧密码数据');
  console.log(errO, '旧密码数据错误');
  if (errO) {
    next([errO.sqlMessage, '查询密码请求失败'])
    return;
  };
  if (resultsO.length === 0) {
    next('当前密码输入错误')
    return;
  };
  //新密码再更新
  let sqlN = `UPDATE e_member set password='${md5(md5(passNew))}' WHERE mid='${mid}'`

  let [err, results] = await Db(sqlN);
  console.log(err, '修改密码失败');
  console.log(results, '修改密码');
  if (err) {
    next([err.sqlMessage, '修改密码请求失败'])
    return;
  };
  res.send({
    status: 200,
    msg: '修改密码成功'
  });
})





module.exports = router;